package com.sphd.education.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.activitys.LessonsHistoryActivity;
import com.sphd.education.adapter.LessonAdapter;
import com.sphd.education.base.BaseFragment;
import com.sphd.education.info.LessonInfo;
import com.sphd.education.info.MyInfo;
import com.sphd.education.interfaces.FragmentInterface;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 课程
 * Created by Administrator on 2015/10/12.
 */
public class LessonFragment extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.my_history_lessons)
    TextView myHistoryLessons;
    @Bind(R.id.recyclerview_mylesson)
    RecyclerView myLessonRecyclerView;
    @Bind(R.id.imageView)
    ImageView imageView;
    @Bind(R.id.textView3)
    TextView textView3;
    @Bind(R.id.button)
    Button button;
    private String Tag = "LessonFrtagment";
    private FragmentInterface fragmentInterface;
    private View rootView;
    private LinearLayoutManager layoutManager;
    private LessonAdapter lessonAdapter;
    private List<LessonInfo> lessonInfoList;
    private Context context;
    @Bind(R.id.my_RefreshLayout)
    SwipeRefreshLayout myRefreshLayout;

    public static LessonFragment newInstance(Bundle bundle) {
        LessonFragment fragment = new LessonFragment();
        fragment.setArguments(bundle);//传值判断是那个fragment
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_lesson_layout, container, false);
        ButterKnife.bind(this, rootView);
        myRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        lessonInfoList = new ArrayList<>();
        layoutManager = new LinearLayoutManager(context);
        myLessonRecyclerView.setLayoutManager(layoutManager);
        lessonAdapter = new LessonAdapter(getActivity(), lessonInfoList, R.layout.layout_lesson_item);
        myLessonRecyclerView.setAdapter(lessonAdapter);
        myNet();
        myHistoryLessons.setOnClickListener(this);
        myRefreshLayout.setOnRefreshListener(this);
        return rootView;
    }

    @Override
    public void onRefresh() {
        lessonInfoList.clear();
        myNet();
    }

    // 接收activity传递过来的接口子类对象
    public void setCallBack(FragmentInterface fragmentInterface) {
        this.fragmentInterface = fragmentInterface;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 跳转到历史课程
     */
    @Override
    public void onClick(View v) {
        MyInfo myInfo = DataSupport.findLast(MyInfo.class);
        if (myInfo == null || myInfo.getUserid() == 0) {
            EducationUrl.showToast(context, "尚未登录，请登录后查看");
        } else {
            Intent intent = new Intent(getActivity(), LessonsHistoryActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void myNet() {
        showMyDialog();
        StringRequest getMyAddNameLessonStringRequest = new StringRequest(Request.Method.POST,
                EducationUrl.HttpTitle + EducationUrl.MyCourse,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        getList(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                myRefreshLayout.setRefreshing(false);
                dismissMyDialog();
                imageView.setVisibility(View.VISIBLE);
                textView3.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                MyInfo myInfo = DataSupport.findLast(MyInfo.class);
                if (myInfo != null && myInfo.getUserid() != 0) {
                    map.put("memberId", myInfo.getUserid() + "");
                }
                return map;
            }
        };
        getMyAddNameLessonStringRequest.setTag("mylesson");
        EducationApplication.getRequestQueue().add(getMyAddNameLessonStringRequest);
    }

    @Override
    public void getList(String string) {
        try {
            JSONArray jsonArray = new JSONArray(string);
            if (jsonArray.length()!=0){
                imageView.setVisibility(View.GONE);
                textView3.setVisibility(View.GONE);
                button.setVisibility(View.GONE);
            }else {
                imageView.setVisibility(View.VISIBLE);
                textView3.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
            }
            Log.e("string", string + "");
            Log.e("jsonArray", jsonArray.length() + "");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                LessonInfo lessonInfo = new LessonInfo();
                lessonInfo.setLesson_id(jsonObject.getInt("id"));
                lessonInfo.setName(jsonObject.getString("lessonName"));
                lessonInfo.setBanji(jsonObject.getString("name"));
                if (jsonObject.has("organization")) {
                    lessonInfo.setSchoolName(new JSONObject(jsonObject.getString("organization")).getString("name"));
                    lessonInfo.setSchoolid(new JSONObject(jsonObject.getString("organization")).getInt("id"));
                }
                lessonInfo.setPeriod(jsonObject.getString("period"));
                lessonInfo.setState(jsonObject.getInt("state"));
                lessonInfoList.add(lessonInfo);
            }
            lessonAdapter.notifyDataSetChanged();
            Log.e("lessonInfoList", lessonInfoList.size() + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        dismissMyDialog();
        myRefreshLayout.setRefreshing(false);
    }

    @Override
    public void getList(JSONObject jsonObject) {

    }


    @Override
    public void getList(JSONArray jsonArray) {

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = getActivity();
    }
    @OnClick (R.id.button)
    public void jumfinlesson(){
        ToastUtils.MyToast(getContext(),"1");
        fragmentInterface.fragmentItemSelected(1);

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("onResume","onResume");
    }
}
